const pool = require('../utils/utils.js')

module.exports = async function (ctx, next) {
  console.log(ctx.request.body)
  const { userid,books} = ctx.request.body;
  if (userid&&books){
      // 先检查
      let selectStr = 'SELECT * FROM bookCase where userid= ' + userid
      console.log(selectStr)
      let r = await new Promise((resolve, reject) => {
          pool.query(selectStr, (err, result) => {
              if (err) {
                  reject(err)
              } else {
                  resolve(result)
              }
          })
      })
      let queryStr = ''
      if(Array.isArray(r) && r.length > 0){
        queryStr = "UPDATE bookCase SET books=" + JSON.stringify(books) +" where userid=" + userid
      }else{
        queryStr = "INSERT INTO bookCase (userid,books) VALUES (" + userid + "," +  JSON.stringify(books) + ")"
      }
   
    console.log(queryStr);
    let res = await new Promise((resolve, reject) => {
      pool.query(queryStr, (err, result) => {
        if (err) {
          reject(err)
        } else {
          resolve(result)
        }
      })
    })
    ctx.body = {
      code: 200,
      msg: '更新成功'
    }
  }else{
    ctx.body = {
      code: 400,
      msg: '更新失败'
    }
  }
  await next()
}